package com.zhiwei.gateway.service.impl;

import com.zhiwei.common.constant.DatabaseConstants;
import com.zhiwei.common.service.CacheService;
import com.zhiwei.gateway.dao.entity.WhiteList;
import com.zhiwei.gateway.dao.entity.WhiteListExample;
import com.zhiwei.gateway.dao.mapper.WhiteListMapper;
import com.zhiwei.gateway.service.WhiteListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * function
 * author zhiwei.yang
 * time 2020-2-28-17:00
 */
@Service
public class WhiteListServiceImpl implements WhiteListService {

    @Autowired
    private WhiteListMapper whiteListMapper;

    @Autowired
    private CacheService cacheService;

    @Value("${spring.application.name}")
    private String app;
    private String whiteListKey = "whiteList";

    @Override
    public List<String> queryWhiteList(WhiteListExample whiteListExample) {
        List<WhiteList> whiteLists = whiteListMapper.selectByExample(whiteListExample);
        if (CollectionUtils.isEmpty(whiteLists)) {
            return Collections.emptyList();
        }
        return whiteLists.stream().map(WhiteList::getPath).collect(Collectors.toList());
    }

    @Override
    public List<String> queryValidWhiteList() {
        List<String> whiteList = (List<String>) cacheService.getCacheObject(app, whiteListKey);
        if (null != whiteList) {
            return whiteList;
        }
        WhiteListExample whiteListExample = new WhiteListExample();
        WhiteListExample.Criteria criteria = whiteListExample.createCriteria();
        criteria.andEnableFlagEqualTo(DatabaseConstants.ENABLE);
        whiteList = this.queryWhiteList(whiteListExample);
        cacheService.putCacheObject(app, whiteListKey, whiteList);
        return whiteList;
    }

    @Override
    public int addWhiteList(WhiteList whiteList) {
        if (null == whiteList) {
            return 0;
        }
        int result = whiteListMapper.insert(whiteList);
        cacheService.removeCacheObject(app, whiteListKey);
        return result;
    }
}
